<template>
  <div>
    <!-- show-checkbox: 显示复选框组件 -->
    <!-- check-strictly: 让父子组件互不关联 -->
    <el-tree
      ref="roleTree"
      show-checkbox
      check-strictly
      default-expand-all
      node-key="id"
      :data="permissionList"
      :props="{label: 'name'}"
    />

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { getRoleId, assignPerm } from '@/api/setting'
import { transListToTree } from '@/utils/index'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      permissionList: [] // 权限列表
    }
  },
  created() {
    // 调用获取权限信息的方法
    this.getPermissionList()
    // 调用获取某一角色的权限
    this.getRoles()
  },
  methods: {
    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },

    // 设置权限确定按钮
    async setRolesBtn() {
      // 获取已选择节点
      const permIds = this.$refs.roleTree.getCheckedKeys()
      // 调用 API
      const res = await assignPerm({ id: this.roleId, permIds })
      // 给用户提示, 关闭弹框
      this.$message.success(res.message)
      this.$emit('close')
    },

    // 获取权限信息
    async getPermissionList() {
      const res = await getPermissionList()
      this.permissionList = transListToTree(res.data, '0')
    },

    // 调用获取某一角色的权限
    async getRoles() {
      const res = await getRoleId(this.roleId)
      this.$refs['roleTree'].setCheckedKeys(res.data.permIds)
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
